import 'package:flutter/foundation.dart';
import '../models/question.dart';
import '../models/answer.dart';
import 'api_service.dart';

class QuestionProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();

  List<Question> _questions = [];
  int _currentPage = 1;
  int _totalPages = 1;
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';

  // Getters
  List<Question> get questions => _questions;
  bool get isLoading => _isLoading;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;
  bool get hasMorePages => _currentPage < _totalPages;

  // Load initial questions
  Future<void> loadQuestions(int rank, int type) async {
    _isLoading = true;
    _hasError = false;
    notifyListeners();

    try {
      final result = await _apiService.getQuestions(1, rank, type);
      _questions = result['questions'];
      _totalPages = result['totalPage'];
      _currentPage = 1;
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // Load more questions
  Future<void> loadMoreQuestions(int rank, int type) async {
    if (_isLoading || _currentPage >= _totalPages) return;

    _isLoading = true;
    notifyListeners();

    try {
      final nextPage = _currentPage + 1;
      final result = await _apiService.getQuestions(nextPage, rank, type);
      _questions.addAll(result['questions']);
      _currentPage = nextPage;
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // Reset state
  void reset() {
    _questions = [];
    _currentPage = 1;
    _totalPages = 1;
    _isLoading = false;
    _hasError = false;
    _errorMessage = '';
    notifyListeners();
  }
}
